package com.mall.user.services;

import com.alibaba.fastjson.JSON;
import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.IRegisterService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.MemberConverter;
import com.mall.user.converter.UserVerifyConverter;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.UserRegisterRequest;
import com.mall.user.dto.UserRegisterResponse;
import com.mall.user.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * @Classname RegisterServiceImpl
 * @Description 注册逻辑
 * @Date 2021/5/22 15:44
 * @Created by virus
 */
@Service
@Component
@Slf4j
public class RegisterServiceImpl implements IRegisterService {

    private static final String subject = "CSMall用户激活";

    private static final String url = "http://localhost:8080/user/verify?uid=";

    private static final String username = "debugteam@163.com";

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserVerifyMapper userVerifyMapper;

    @Autowired
    private MemberConverter memberConverter;

    @Autowired
    private UserVerifyConverter userVerifyConverter;

    @Autowired
    private JavaMailSender mailSender;

    public RegisterServiceImpl() {
    }

    @Override
    public UserRegisterResponse register(UserRegisterRequest request) {
        UserRegisterResponse response = new UserRegisterResponse();
        try {
            // 新用户信息插入用户表
            request.requestCheck();
            Member member = memberConverter.registerReq2Member(request);
            validUniqueUsernameAndEmail(member);
            member.setPassword(DigestUtils.md5DigestAsHex(member.getPassword().getBytes()));
            member.setCreated(new Date());
            member.setUpdated(new Date());
            int affectedMemberRow = memberMapper.insertSelective(member);
            if (affectedMemberRow != 1) {
                response.setCode(SysRetCodeConstants.USER_REGISTER_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_FAILED.getMessage());
                return response;
            }
            // 插入用户验证表
            UserVerify userVerify = userVerifyConverter.registerReq2UserVerify(request);
            userVerify.setRegisterDate(new Date());
            userVerify.setIsVerify("N");
            userVerify.setIsExpire("N");
            int affectedUserVerifyRow = userVerifyMapper.insertSelective(userVerify);
            if (affectedUserVerifyRow != 1) {
                response.setCode(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getCode());
                response.setMsg(SysRetCodeConstants.USER_REGISTER_VERIFY_FAILED.getMessage());
                return response;
            }
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            log.info("用户注册成功，注册参数request:{}", JSON.toJSONString(request));

            // 邮件注册
            new Thread(new Runnable() {
                @Override
                public void run() {
                    sendEmail(request.getUuid(), request);
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("RegisterServiceImpl.register occur Exception : " + e);
            ExceptionProcessorUtils.wrapperHandlerException(response, e);
        }
        return response;
    }

    /**
     * 验证member表中username或email是否唯一
     * @param member
     */
    private void validUniqueUsernameAndEmail(Member member) {
        Example example = new Example(Member.class);
        example.createCriteria().orEqualTo("username", member.getUsername())
                .orEqualTo("email", member.getEmail());
        List<Member> members = memberMapper.selectByExample(example);
        if (!members.isEmpty()) {
            throw new ValidateException(SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getCode(),
                    SysRetCodeConstants.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }

    /**
     * 发送激活邮件
     * @param uuid
     * @param request
     */
    private void sendEmail(String uuid, UserRegisterRequest request) {

        SimpleMailMessage message = new SimpleMailMessage();

        message.setSubject(subject);
        message.setFrom(username);
        message.setTo(request.getEmail());
        message.setText(url + uuid + "&username=" + request.getUserName());
        mailSender.send(message);
    }
}
